import axios from 'axios'
import type { PlaylistInfo, SongInfo, AlbumInfo } from '@/types'

// 创建 axios 实例
const instance = axios.create({
  baseURL: '/api',
  timeout: 10000,
  withCredentials: true
})

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    console.log('API Response:', {
      url: response.config.url,
      method: response.config.method,
      params: response.config.params,
      data: response.data
    })

    // 检查响应数据结构
    const { data } = response
    if (data && typeof data === 'object') {
      if ('code' in data) {
        if (data.code === 200) {
          return data
        } else {
          return Promise.reject(new Error(data.message || '请求失败'))
        }
      }
      return data
    }
    return data
  },
  (error) => {
    console.error('API Error:', {
      url: error.config?.url,
      method: error.config?.method,
      params: error.config?.params,
      error: error.message,
      response: error.response?.data
    })
    return Promise.reject(error)
  }
)

export interface Response<T> {
  code: number
  message?: string
  data: T[] | {
    list: T[]
    total?: number
  }
}

export interface SingleResponse<T> {
  code: number
  message?: string
  data: T
}

// 歌单相关接口
const playlist = {
  // 获取歌单详情
  getPlaylistDetail(id: string) {
    return instance.get<SingleResponse<PlaylistInfo>>(`/playlist?id=${id}`)
  },
  
  // 获取推荐歌单
  getRecommendPlaylists(params: { pageNo: number, type: number }) {
    return instance.get<Response<PlaylistInfo>>('/recommend/playlist', { 
      params: { 
        pageNo: params.pageNo,
        type: params.type 
      } 
    })
  }
}

// 歌曲相关接口
const song = {
  // 获取歌曲详情
  getSongDetail(cid: string) {
    return instance.get<SingleResponse<SongInfo>>(`/song?cid=${cid}`)
  },
  
  // 获取歌曲 URL
  getSongUrl(cid: string) {
    return instance.get<SingleResponse<string>>('/song/url', { params: { cid } })
  },

  // 获取最新歌曲
  getNewSongs(params: { pageNo: number, pageSize: number }) {
    return instance.get<Response<SongInfo>>('/new/songs', { 
      params: {
        pageNo: params.pageNo,
        pageSize: params.pageSize
      }
    })
  }
}

// 专辑相关接口
const album = {
  // 获取专辑详情
  getAlbumDetail(id: string) {
    return instance.get<SingleResponse<AlbumInfo>>(`/album?id=${id}`)
  },

  // 获取最新专辑
  getNewAlbums(params: { pageNo: number, pageSize: number }) {
    return instance.get<Response<AlbumInfo>>('/new/albums', { 
      params: {
        pageNo: params.pageNo,
        pageSize: params.pageSize
      }
    })
  }
}

export const playlistAPI = playlist
export const songAPI = song
export const albumAPI = album 